from django import forms
from django.core.exceptions import ValidationError
from user.models import VSession, Company, WarZone, User
import pdb


def token_check(value):
    # 验证token必须存在
    sessionList = VSession.objects.filter(token=value)
    if not sessionList.exists():
        errMsg = 'token Error'
        isValidOk = False
        raise ValidationError(errMsg)
    else:
        session = sessionList[0]


def user_check(value):
    # 验证token必须存在
    is_num_by_except(value)
    userList = User.objects.filter(id=value)
    if not userList.exists():
        errMsg = 'userId Error'
        raise ValidationError(errMsg)


def warZoneId_check(value):
    # 验证单位id必须存在
    if value != -1:
        is_num_by_except(value)
        warZone = WarZone.objects.filter(pk=value)
        if not warZone.exists():
            errMsg = 'warZoneId Error'
            raise ValidationError(errMsg)


def companyId_check(value):
    # 验证单位id必须存在
    if value != -1:
        is_num_by_except(value)
        company = Company.objects.filter(pk=value)
        if not company.exists():
            errMsg = 'companyId Error'
            raise ValidationError(errMsg)


def is_num_by_except(num):
    try:
        int(num)
        return True
    except ValueError:
        errMsg = 'value not int'
        raise ValidationError(errMsg)


def maxItem_check(value):
    if value < 1:
        errMsg = 'maxItem Error'
        raise ValidationError(errMsg)


def page_check(value):
    if value < 1:
        errMsg = 'page Error'
        raise ValidationError(errMsg)


class RegisterForm(forms.Form):
    username = forms.CharField(max_length=20)
    password = forms.CharField(max_length=20)
    phone = forms.CharField(max_length=20)
    name = forms.CharField(max_length=20)
    userType = forms.CharField(max_length=20)
    warZoneId = forms.IntegerField(validators=[warZoneId_check])
    companyId = forms.IntegerField(validators=[companyId_check])

    def clean_username(self):
        username = self.cleaned_data['username']
        user = User.objects.filter(username=username)
        # pdb.set_trace()
        if len(user) == 1:
            errMsg = 'username is exist'
            raise ValidationError(errMsg)
        return username


class LoginForm(forms.Form):
    username = forms.CharField(max_length=20, required=False)
    password = forms.CharField(max_length=50, required=False)
    isSingleLogin = forms.IntegerField()
    code = forms.CharField(max_length=10, required=False)
    accessToken = forms.CharField(max_length=100, required=False)
    refreshToken = forms.CharField(max_length=100, required=False)
    systemType = forms.CharField(max_length=20)

    # def clean_username(self):
    #     username = self.cleaned_data['username']
    #     user = User.objects.filter(username=username)
    #     # pdb.set_trace()
    #     if len(user) != 1:
    #         errMsg = 'username not exist'
    #         raise ValidationError(errMsg)
    #     return username

    def clean(self):
        systemType = self.cleaned_data['systemType']
        if systemType != '' and (systemType not in ['1', '2', '3']):
            errMsg = 'system Error'
            raise ValidationError(errMsg)
        return self.cleaned_data


class LogoutForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])


class GetValidImg(forms.Form):
    pass


class IsOnlineForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])


class IsUserSystemWebForm(forms.Form):
    pass


class updateTokenForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    newToken = forms.CharField(max_length=100)


class SupervisorUserListForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    userType = forms.CharField(required=False, max_length=10)
    search = forms.CharField(required=False, max_length=50)
    page = forms.IntegerField(validators=[page_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])

    def clean(self):
        token = self.cleaned_data['token']
        sessionList = VSession.objects.filter(token=token)
        if not sessionList[0].user.isSupervisor:
            errMsg = 'Not SVP'
            raise ValidationError(errMsg)
        return self.cleaned_data


class SupervisorEditForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    userType = forms.CharField(max_length=10)
    userId = forms.CharField(max_length=10, validators=[user_check])

    def clean(self):
        token = self.cleaned_data['token']
        userType = self.cleaned_data['userType']
        sessionList = VSession.objects.filter(token=token)
        if not sessionList[0].user.isSupervisor:
            errMsg = 'Not SVP'
            raise ValidationError(errMsg)
        if userType not in ['1', '2', '3']:
            errMsg = 'UserType Error'
            raise ValidationError(errMsg)
        return self.cleaned_data


class SearchUserForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check], required=False)
    userName = forms.CharField(max_length=100, required=False)
